import { createCrudApi } from '../factories/createCrudApi'
import { request } from '../request'
import type {
  VisitorSheet,
  VisitorSheetWithDetails,
  VisitorSheetCreate,
  VisitorSheetUpdate,
} from '../types'

/**
 * 访客单筛选参数
 */
interface VisitorSheetFilter {
  lead_id?: number
  property_id?: number
  agent_id?: number
  start_date?: string
  end_date?: string
  intention?: string
  [key: string]: unknown
}

/**
 * 访客单管理 API
 * 基础 CRUD 使用 createCrudApi 工厂生成
 * 额外的自定义方法单独添加
 */
const baseCrudApi = createCrudApi<
  VisitorSheet,
  VisitorSheetCreate,
  VisitorSheetUpdate,
  VisitorSheetFilter
>('v1/visitor-sheets/')

export const visitorSheetApi = {
  ...baseCrudApi,

  /**
   * 重写 getById 以返回包含关联实体的详情
   */
  getById(id: number): Promise<VisitorSheetWithDetails> {
    return request.get(`v1/visitor-sheets/${id}`)
  },

  /**
   * 获取满意度统计（自定义方法）
   */
  getSatisfactionStats(params?: {
    property_id?: number
    agent_id?: number
  }): Promise<{ avg_satisfaction: number; total_visits: number }> {
    return request.get('v1/visitor-sheets/stats/satisfaction', { params })
  },

  /**
   * Phase 2: 从备注提取访客单信息（AI辅助）
   */
  extractInfo(params: {
    notes: string
    community_name?: string
  }): Promise<{
    satisfaction?: number
    intention?: 'high' | 'medium' | 'low'
    pros_tags?: string
    cons_tags?: string
    visit_time?: string
    duration_minutes?: number
    confidence: number
    extraction_method: string
  }> {
    return request.post('v1/visitor-sheets/extract-info', null, { params })
  },

  /**
   * Phase 2: 快捷创建访客单（快捷模式）
   */
  quickCreate(data: {
    lead_id: number
    property_id: number
    agent_id: number
    visit_date: string
    quick_notes: string
    satisfaction?: number
    intention?: string
    pros_tags?: string
    cons_tags?: string
    visit_time?: string
    duration_minutes?: number
  }): Promise<VisitorSheet> {
    return request.post('v1/visitor-sheets/quick-create', data)
  },
}
